package com.nercel.dsj.gksales.api.controller;

import com.github.pagehelper.PageInfo;
import com.nercel.dsj.gksales.constant.Env;
import com.nercel.dsj.gksales.exception.ResponseCode;
import com.nercel.dsj.gksales.exception.RestApiException;
import com.nercel.dsj.gksales.model.ListResult;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * Base api controller
 */
@RestController
public class BaseApiController {

    @Value("${app.host}")
    private String siteHost;

    @Value("${spring.profiles.active}")
    private String env;

    /**
     * 分布式列表结果集
     * @param pageInfo
     * @return
     */
    protected ListResult listResult(PageInfo pageInfo) {
        return ListResult.fromPageInfo(pageInfo);
    }

    /**
     * 得到request对象
     */
    public HttpServletRequest getRequest() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

        return request;
    }

    public String getBasePath(){
        HttpServletRequest request = this.getRequest();
        String path = request.getContextPath();
        String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
        if (!StringUtils.isEmpty(siteHost)){
            basePath = siteHost;
        }
        return basePath;
    }

    public String url(String path){
        return getBasePath() + path;
    }

    protected boolean isProd(){
        return env.equals(Env.PROD);
    }

    protected Integer getUserId(){
        if(SecurityUtils.getSubject().getPrincipals() == null || SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal() == null){
            throw new RestApiException(ResponseCode.FORBIDDEN);
        }
        return Integer.valueOf((String) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal());
    }

}
